package com.we.risk.logoff.apply;

import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

public class TableLendAuditRecord {
    public static final String KFKTABLE = "fdm.hhl01_lend_audit_record";
    public static final String QUERYSQL =
            "select loan_id, updated_at, "
                    + "status "
                    + "from "
                    + KFKTABLE
                    + " where deleted_at is null "
                    + "and status is not null "
                    + "and loan_id is not null "
                    + "and updated_at is not null ";

    public long loan_id;
    public int status;
    public int updated_at;

    public TableLendAuditRecord(long loan_id, int status, int updated_at) {
        this.loan_id = loan_id;
        this.status = status;
        this.updated_at = updated_at;
    }

    public TableLendAuditRecord() {}

    public static TableLendAuditRecord init(long loan_id) {
        return new TableLendAuditRecord(loan_id, -1, 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableLendAuditRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableLendAuditRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableLendAuditRecord.class);

        SingleOutputStreamOperator<String> out = inputStream.filter(new FilterFunction<Tuple2<Boolean, TableLendAuditRecord>>() {
            @Override
            public boolean filter(Tuple2<Boolean, TableLendAuditRecord> value) throws Exception {
                return value.f0;
            }
        }).uid("TableLendAuditRecord-filter")
        .keyBy(new KeySelector<Tuple2<Boolean, TableLendAuditRecord>, Long>() {
            @Override
            public Long getKey(Tuple2<Boolean, TableLendAuditRecord> value) throws Exception {
                return value.f1.getLoan_id();
            }
        })
        .flatMap(new RichFlatMapFunction<Tuple2<Boolean, TableLendAuditRecord>, String>() {
            ValueState<TableLendAuditRecord> tableLendAuditRecordVState;

            @Override
            public void open(Configuration parameters) throws Exception {
                tableLendAuditRecordVState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<TableLendAuditRecord>("TableLendAuditRecordVState", TableLendAuditRecord.class));
            }

            @Override
            public void flatMap(Tuple2<Boolean, TableLendAuditRecord> value, Collector<String> out) throws Exception {
                long loan_id = value.f1.getLoan_id();
                int status = value.f1.getStatus();
                int updated_at = value.f1.getUpdated_at();

                TableLendAuditRecord tmpState = tableLendAuditRecordVState.value();
                TableLendAuditRecord curState = (tmpState == null ? init(loan_id) : tmpState);

                if (updated_at > curState.getUpdated_at()) {
                    if (status != curState.status) {
                        curState = value.f1;
                        JSONObject outJson = new JSONObject();
                        outJson.put("loan_id", loan_id);
                        outJson.put("status", status);

                        out.collect(outJson.toString());
                    }

                    curState.updated_at = updated_at;
                    tableLendAuditRecordVState.update(curState);
                }
            }
        });
        return out;
    }

    public long getLoan_id() {
        return loan_id;
    }

    public int getStatus() {
        return status;
    }

    public int getUpdated_at() {
        return updated_at;
    }
}
